package org.distributed.security.client1.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SystemUserController {

	@GetMapping(value="/userInfo")
	@PreAuthorize("hasAnyAuthority('userInfo')")
	public String userInfo(){
		return getUsername() + " 访问资源userInfo";
	}
	
	/**
	 * 获取当前登录用户名
	 */
	private String getUsername() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (!authentication.isAuthenticated()) {
			return null;
		}
		Object principal = authentication.getPrincipal();
		String username = null;
		if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		return username;
	}
}
